package com.logic.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.logic.rpc.AccessRpcUtils;
import com.pjc.config.BaseEnums;
import com.pjc.config.GlobalKey;
import com.pjc.config.RpcReturnCode;
import com.pjc.dao.SysMsgDao;
import com.pjc.dao.UserDao;
import com.pjc.dao.UserStatusDao;
import com.pjc.model.User;
import com.pjc.model.UserStatus;
import com.pjc.model.chat.SysMsg;
import com.pjc.thrift.TInnerProto;
import com.pjc.utils.Utils;

/**
 * 消息业务处理类
 * 
 * @author 王畅
 * @version 创建时间：2015-6-18 下午04:53:58
 */
public class MsgService {

	protected final static Logger log = LoggerFactory.getLogger(MsgService.class);

	/**
	 * 推送系统消息
	 * 
	 * @author 王畅
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static int pushSystemMsg(String data) throws Exception {

		SysMsg msg = (SysMsg) Utils.JSON2Object(data, SysMsg.class);
		if (msg == null) {
			return RpcReturnCode.OK;
		}
		if (msg.getType() != BaseEnums.NoticeTypeEnum.Notice_FlowData.getId()) {

			UserStatus userStatus = UserStatusDao.getUserStatus(msg.getToUserId(), msg.getAppId().toLowerCase() + ":user:status:");
			if ((userStatus == null) || (userStatus.getServerId() == 0)) { // 离线状态
				User toUser = UserDao.getUser(msg.getToUserId(), msg.getAppId().toLowerCase());
				if (toUser == null) {
					return RpcReturnCode.OK;
				}
				SysMsgDao.saveSysMsg(msg);
				return RpcReturnCode.OK;
			}
			TInnerProto proto = new TInnerProto();
			proto.setId(GlobalKey.LogicToAccess.TRANS_SYS_MSG);
			proto.setData(Utils.object2JSON(msg));
			AccessRpcUtils.sendToAccessSrv(msg.getAppId().toLowerCase(), userStatus.getServerId(), proto);
			SysMsgDao.saveSysMsg(msg);
		} else {
			TInnerProto proto = new TInnerProto();
			proto.setId(GlobalKey.LogicToAccess.TRANS_SYS_MSG);
			proto.setData(Utils.object2JSON(msg));
			AccessRpcUtils.broadcastMsg(proto);
		}
		return RpcReturnCode.OK;
	}

	/**
	 * 跨服务器踢人方法
	 * 
	 * @author 王畅
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static int handlerKickUser(String data) throws Exception {
		JSONObject json = JSONObject.parseObject(data);
		TInnerProto proto = new TInnerProto();
		proto.setId(GlobalKey.LogicToAccess.KICK_USER);
		proto.setData(data);
		AccessRpcUtils.sendToAccessSrv(json.getString("appId").toLowerCase(), json.getIntValue("serverId"), proto);
		return RpcReturnCode.OK;
	}

}
